package com.keqing.tomato;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.keqing.tomato.service.TimerService;

public class LandscapeActivity extends AppCompatActivity {
    private TextView tvTime;
    private BroadcastReceiver broadcastReceiver;
    private TimerService timerService;
    private final ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("tomato", "ServiceConnection - onServiceConnected()");
            TimerService.TimerServiceBinder binder = (TimerService.TimerServiceBinder) service;
            timerService = binder.getTimerService();
            CountDownTimer countDownTimer = timerService.getCountDownTimer();
            if(countDownTimer == null){
                Bundle bundle = getIntent().getExtras();
                String time = bundle.getString("time");
                tvTime.setText(time);
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("tomato", "ServiceConnection - onServiceDisconnected()");

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_landscape);
        Log.e("tomato", "LandscapeActivity - onCreate()");
        tvTime = findViewById(R.id.tv_time);
        Intent intent = new Intent(getApplicationContext(), TimerService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

        registerBroadcastReceivers();
    }

    private void registerBroadcastReceivers() {
        this.broadcastReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getExtras();
                String minSec = bundle.getString("minSec");
                tvTime.setText(minSec);
                int what = bundle.getInt("what");
                if (what == TimerService.time_ticking) {
                }
                if (what == TimerService.time_finished) {
//                    handleTimeTask();
                }
            }
        };
        registerReceiver(this.broadcastReceiver, new IntentFilter("timer"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("tomato", "LandscapeActivity - onDestroy()");
        unbindService(conn);
        unregisterReceiver(broadcastReceiver);
    }
}